package com.xzjt.entity;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yuandong
 * @date 2021/9/4 9:21
 */
public class MenuTree {

    private List<SysMenu> sysMenuList = new ArrayList<SysMenu>();
    public MenuTree(List<SysMenu> sysMenuList) {
        this.sysMenuList = sysMenuList;
    }

    //建立树形结构
    public List<SysMenu> builTree(){
        List<SysMenu> treeSysMenus =new  ArrayList<SysMenu>();
        for(SysMenu sysMenuNode : getRootNode()) {
            sysMenuNode =buildChilTree(sysMenuNode);
            treeSysMenus.add(sysMenuNode);
        }
        return treeSysMenus;
    }

    //递归，建立子树形结构
    private SysMenu buildChilTree(SysMenu pNode){
        List<SysMenu> chilSysMenus =new  ArrayList<SysMenu>();
        for(SysMenu sysMenuNode : sysMenuList) {
            if(sysMenuNode.getPid().equals(pNode.getMenuId())) {
                chilSysMenus.add(buildChilTree(sysMenuNode));
            }
        }
        pNode.setChildren(chilSysMenus);
        return pNode;
    }

    //获取根节点
    private List<SysMenu> getRootNode() {
        List<SysMenu> rootSysMenuLists =new  ArrayList<SysMenu>();
        for(SysMenu sysMenuNode : sysMenuList) {
            if(sysMenuNode.getPid().equals(0)) {
                rootSysMenuLists.add(sysMenuNode);
            }
        }
        return rootSysMenuLists;
    }
}
